from collections import OrderedDict

from .models import GoodsChannel


def get_categories():
    """
    获取商品频道及分类菜单
    使用有序字典保存类别的顺序
    """
    # categories = {
    #     1: { # 组1
    #         'channels': [{'id':, 'name':, 'url':},{}, {}...],
    #         'sub_cats': [{'id':, 'name':, 'sub_cats':[{},{}]}, {}, {}, ..]
    #     },
    #     2: { # 组2
    #
    #     }
    # }
    # 创建一个有序的字典用来储存商品分类
    categories = OrderedDict()
    # 按照组号查询商品频道  sequence排序   queryset对象
    channels = GoodsChannel.objects.order_by('group_id','sequence')
    # for循环遍历商品频道
    for channel in channels:
        # group-id  为商品频道的组号
        group_id = channel.group_id

        #  判断当前组是否在创建好的 有序字典中
        if group_id not in categories:
            categories[group_id] = {'channels':[],'sub_cats':[]}

        cat1 = channel.category # 当前频道的类别

        # 追加当前频道
        categories[group_id]['channels'].append({
            'id':cat1.id,
            'name':cat1.name,
            'url':channel.url
        })
        # 构建当前频道的子类别
        for cat2 in cat1.goodscategory_set.all():
            cat2.sub_cats = []
            for cat3 in cat2.goodscategory_set.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]['sub_cats'].append(cat2)

    return categories


